<?php

namespace App\Http\Controllers\Wx;

use App\Driver;
use DB;
use Illuminate\Http\Request;

class DriverController extends Controller
{
    public function index() {
        $member = $this->member();
        $driver = Driver::where('openid',$member->openid)
            ->first();
        if($driver) {
            return view('wx.driver',['driver'=>$driver]);
        } else {
            return redirect()->route('driver.reg')->with('msg','请先注册成为司机！');
        }
    }

    public function reg(Request $request) {

        $member = $this->member();
        $driver = Driver::where('openid',$member->openid)
            ->first();
        if($driver) {
            return redirect()->route('driver')->withErrors('你已经注册过司机！');
        }

        if($request->isMethod('get')) {
            return view('wx.driver_reg');
        } else {

            //验证码验证
            $real_vcode = session('vcode');
            $vcode = $request->input('vcode');

            if($real_vcode != $vcode ) {
                return back()->withInput()->withErrors('验证码错误！');
            }

            $driver = Driver::whereNull('openid')
                ->where('phone',$request->input('phone'))
                ->first();
            if(!$driver) {
                return back()->withErrors('手机号码不存在！');
            }

            $driver->openid = $member->openid;
            $driver->save();

            return redirect()->route('driver')->with('msg','司机注册成功！');
        }
    }

    public function end_trip(Request $request) {
        $member = $this->member();
        $driver = Driver::where('openid',$member->openid)
            ->first();
        if(!$driver) {
            return redirect()->route('driver.reg')->with('msg','请先注册成为司机！');
        }
//        dd($driver->free == $driver->num);
//        if($driver->free == $driver->num) {
//            return back()->withErrors('行程结束失败，当前乘客数量为0！');
//        }

        try {

            DB::beginTransaction();

            DB::table('orders')
                ->where('status', 2)
                ->where('driver_id', $driver->id)
                ->update([
                    'status' => 3
                ]);

            $driver->free = $driver->num;
            $driver->return_trip = ($driver->return_trip == 1)?0:1;
            $driver->save();

            DB::commit();

            return redirect()->route('driver')->with('msg','行程已结束！');

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('司机结束行程失败！'.$e->getMessage());
        }
    }
}
